﻿using Simple.Common.Authentication;

namespace Simple.Services.System
{
    public class BusinessBaseService
    {
        private readonly ISimpleService _simpleService;

        public ICurrentUserService _currentUser { get; set; }

        public BusinessBaseService(ISimpleService simpleService)
        {
            _simpleService = simpleService;
            _currentUser = _simpleService.GetService<ICurrentUserService>();
        }

        public async Task<IQueryable<TSource>> OrganizationFilter<TSource>(IQueryable<TSource> source) where TSource : IOrganization
        {
            // 方案一：同时查看授权机构的数据
            //var dataScope = await _simpleService.GetService<UserService>().GetUserDataScopeAsync();
            //if (dataScope == null || dataScope.AdminType == AdminType.SuperAdmin || dataScope.AdminType == AdminType.Admin)
            //{
            //    return source;
            //}
            //var orgIds = new List<Guid>();
            //if (dataScope != null && dataScope.UserDataScopes.Any())
            //{
            //    var ids = dataScope.UserDataScopes.Select(s => s.OrganizationId).ToList();
            //    orgIds.AddRange(ids);
            //}
            //if (dataScope?.OrganizationId != null && !orgIds.Contains(dataScope.OrganizationId.Value))
            //{
            //    orgIds.Add(dataScope.OrganizationId.Value);
            //}

            //if (orgIds.Any())
            //{
            //    if (orgIds.Count == 1)// 命中索引
            //        source = source.Where(s => orgIds[0] == s.OrganizationId);
            //    else
            //        source = source.Where(s => s.OrganizationId.HasValue && orgIds.Contains(s.OrganizationId.Value));
            //}
            //return source;

            // 方案二：只能查看单个机构的数据，查看其他授权机构需要切换
            //var orgId = _simpleService.GetService<ICurrentUserService>()?.OrganizationId;
            //if (orgId != null)
            //    source = source.Where(s => orgId == s.OrganizationId);
            //return source;

            // 方案三：根据当前选择的机构获取数据
            var orgService = _simpleService.GetService<OrganizationService>();
            var orgList = await orgService.GetEntitysAsync();
            var userOrgEntity = orgService.GetParentOrganization(orgList, _currentUser.OriginalOrgId);
            var orgIds = new List<Guid>();
            // 超级管理员直接获取当前选择机构下所有子机构
            if (_currentUser.IsSuperAdmin)
            {
                //orgIds = orgService.GetChildrenOrganization(orgList, _currentUser.OrganizationId);
            }
            else
            {
                // 如果当前登录的机构隶属于用户自身所在部门，那就查询用户自身部门和其子部门下的数据
                if (userOrgEntity?.Id == _currentUser.OrganizationId)
                {
                    orgIds = orgService.GetChildrenOrganization(orgList, _currentUser.OriginalOrgId);
                }
                // 如果登录的机构不属于自身所在部门，那就说明是通过数据授权得到的机构权限，只能查询授权部门的数据（不包含子部门）
                var dataScope = await _simpleService.GetService<UserService>().GetUserDataScopeAsync();
                if (dataScope != null && dataScope.UserDataScopes.Any())
                {
                    var curAllOrgs = orgService.GetChildrenOrganization(orgList, _currentUser.OrganizationId);
                    var curOrgIds = curAllOrgs.Where(s => dataScope.UserDataScopes.Exists(d => d.OrganizationId == s)).ToList();
                    orgIds.AddRange(curOrgIds);
                }
            }

            if (orgIds.Any())
            {
                orgIds = orgIds.Distinct().ToList();
                if (orgIds.Count == 1)// 命中索引
                    source = source.Where(s => orgIds[0] == s.OrganizationId);
                else
                    source = source.Where(s => s.OrganizationId.HasValue && orgIds.Contains(s.OrganizationId.Value));
            }
            return source;
        }
    }
}
